<template>
  <div class="personnel">
    <div class="row" style="margin-bottom: 12px">
      <el-input
        v-model="searchUsername"
        style="width: 240px; margin-right: 12px"
        placeholder="请输入用户名"
      />
      <el-button type="primary" @click="search">查找</el-button>
    </div>
    <el-table
      :data="
        showTableData.slice(
          (currentPage - 1) * pageSize,
          currentPage * pageSize
        )
      "
      @filter-change="handlerFilterChange"
      row-key="ID"
    >
      <el-table-column prop="ID" label="ID" column-key="ID" />
      <el-table-column prop="Username" label="用户" />
      <el-table-column
        prop="UserGroup"
        label="分会"
        column-key="userGroup"
        :filters="userGroups"
        :filter-method="filterUserGroup"
      />
      <el-table-column
        prop="Status"
        label="角色"
        column-key="status"
        :filters="statuses"
        :filter-method="filterStatus"
      />
      <el-table-column prop="Level" label="等级" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="editUser(scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="deleteUser(scope.row.Username)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin: 10px"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="showTableData.length"
      v-model:current-page="currentPage"
    />
    <el-dialog
      center
      width="30%"
      v-model="editVisible"
      title="修改用户信息"
      class="col center"
    >
      <el-form
        :model="selectedUser"
        label-width="100px"
        style="max-width: 460px"
      >
        <el-form-item label="ID">
          <el-input v-model="selectedUser.ID" disabled />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="selectedUser.Username" disabled />
        </el-form-item>
        <el-form-item label="分会">
          <el-select
            v-model="selectedUser.UserGroup"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="userGroup in userGroups"
              :key="userGroup.value"
              :label="userGroup.text"
              :value="userGroup.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="selectedUser.Status"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="status in statuses"
              :key="status.value"
              :label="status.text"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-input type="number" v-model="selectedUser.Level" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button type="primary" @click="saveUser"> 保存 </el-button>
          <el-button @click="editVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
const editVisible = ref(false)
const showTableData = ref([])
const tableData = ref([])
const searchUsername = ref(null)
const currentPage = ref(1)
const pageSize = ref(15)
const selectedUser = ref({
  ID: '',
  Username: '',
  UserGroup: '',
  Status: '',
  Level: '',
})
const filterStatusTag = ref([])
const filterUserGroupTag = ref([])
const userGroups = [
  {
    text: 'super_admin',
    value: 'super_admin',
  },
  {
    text: 'undefined',
    value: 'undefined',
  },
  {
    text: '铁路分会',
    value: '铁路分会',
  },
  {
    text: '水路分会',
    value: '水路分会',
  },
  {
    text: '公路分会',
    value: '公路分会',
  },
  {
    text: '航空分会',
    value: '航空分会',
  },
  {
    text: '邮政分会',
    value: '邮政分会',
  },

  {
    text: '物流分会',
    value: '物流分会',
  },
  {
    text: '其他',
    value: '其他',
  },
]
const statuses = [
  {
    text: 'super_admin',
    value: 'super_admin',
  },
  {
    text: 'admin',
    value: 'admin',
  },
  {
    text: 'guest',
    value: 'guest',
  },
  {
    text: 'undefined',
    value: 'undefined',
  },
]
// 获取所有用户
const getAllUsers = () => {
  axios
    .get('/api/getAllUser', {
      headers: {
        Authorization: `Bearer ${window.localStorage.getItem('token')}`,
      },
    })
    .then((res) => {
      console.log(res.data.data)
      tableData.value = res.data.data
      showTableData.value = res.data.data
    })
}

// 搜索用户
const search = () => {
  if (
    searchUsername.value === '' ||
    searchUsername.value === undefined ||
    searchUsername.value === null
  ) {
    getAllUsers()
    return
  }
  showTableData.value = tableData.value.filter(
    (uesr: any) => uesr.Username === searchUsername.value
  )
}

const filterUserGroup = (value: string, row: any) => {
  return row.UserGroup === value
}
const filterStatus = (value: string, row: any) => {
  return row.Status === value
}

const editUser = (user: any) => {
  editVisible.value = true
  nextTick(() => {
    selectedUser.value = user
  })
}

const deleteUser = (username: string) => {
  ElMessageBox.confirm('你确定要删除该用户吗？此操作不可逆', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete('/api/delUser', {
          data: {
            username: username,
          },
        })
        .then(() => {
          getAllUsers()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '删除失败，权限不够或不存在用户',
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const saveUser = () => {
  console.log(selectedUser.value)
  axios
    .put('/api/updateUserInfo', {
      username: selectedUser.value.Username,
      status: selectedUser.value.Status,
      user_group: selectedUser.value.UserGroup,
      level: parseInt(selectedUser.value.Level),
    })
    .then((res) => {
      ElMessage.success('修改成功')
      console.log(res)
      editVisible.value = false
    })
    .catch(() => {
      ElMessage.error('修改失败')
    })
}

const getNewShowTableData = () => {
  if (
    filterStatusTag.value.length === 0 &&
    filterUserGroupTag.value.length === 0
  ) {
    showTableData.value = tableData.value
  } else {
    showTableData.value = tableData.value.filter((item: any) => {
      let flag = false
      for (let i = 0; i < filterStatusTag.value.length; i++) {
        if (item.Status === filterStatusTag.value[i]) {
          flag = true
        }
      }
      if (filterUserGroupTag.value.length === 0) {
        return flag
      }
      if (filterStatusTag.value.length === 0) {
        flag = true
      }
      for (let i = 0; i < filterUserGroupTag.value.length; i++) {
        if (item.UserGroup === filterUserGroupTag.value[i] && flag === true) {
          return true
        }
      }
      return false
    })
  }
}

const handlerFilterChange = (filter: any) => {
  console.log(filter)
  filterStatusTag.value =
    filter['status'] === undefined ? filterStatusTag.value : filter['status']

  filterUserGroupTag.value =
    filter['userGroup'] === undefined
      ? filterUserGroupTag.value
      : filter['userGroup']
  getNewShowTableData()
}

onMounted(() => {
  getAllUsers()
})
</script>

<style scoped>
.personnel {
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 10px;
  padding: 24px;
}
.tabs {
  padding: 12px 24px 24px 24px;
}
</style>
